package com.itheima;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(value = "/*", initParams = @WebInitParam(name = "encoding", value = "UTF-8"))
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter......execute");
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String uri = req.getRequestURI();
        System.out.println(req.getRequestURL());
        System.out.println(uri);
        String str = uri.substring(uri.lastIndexOf("/") + 1);
        //放行login.jsp和login
        if("login.jsp".equals(str)||"login".equals(str)){
            filterChain.doFilter(req, resp);
            return;
        }

        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if(user!=null){
            filterChain.doFilter(req, resp);
        }else{
            resp.sendRedirect(req.getContextPath()+ "/login.jsp");
        }
    }
}
